package com.rzico.market.plugin.phoneBill;

import com.rzico.core.entity.SysPlugin;
import com.rzico.core.entity.SysPluginAttribute;
import com.rzico.core.model.PluginAttribute;
import com.rzico.core.service.SysPluginAttributeService;
import com.rzico.market.plugin.PhoneBillPlugin;
import com.rzico.util.CodeGenerator;
import com.rzico.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;


/**
 * Plugin -  豆讯短信
 *
 * @author RZICO.BOOT
 * @version 3.0
 */
@Component("dxPhonePlugin")
public class DxPhonePlugin extends PhoneBillPlugin {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected SysPluginAttributeService sysPluginAttributeService;

    @Override
    public String getName() {
        return "豆讯话费充值";
    }

    @Override
    public String getVersion() {
        return "1.00";
    }

    @Override
    public List<PluginAttribute> getAttributeKeys() {
        List<PluginAttribute> data = new ArrayList<>();
        data.add(new PluginAttribute("custInteId","custInteId",PluginAttribute.STRING_VALUE));//账号
        data.add(new PluginAttribute("secretKey","secretKey",PluginAttribute.STRING_VALUE));//密匙
        return data;
    }

    public SysPlugin setPlugin(SysPlugin sysplugin, String mchId){
        if (null == sysplugin){
            sysplugin = new SysPlugin();
            String sysPluginId = CodeGenerator.getUUID();
            sysplugin.setId(sysPluginId);
            sysplugin.setName("豆讯话费充值");
            sysplugin.setVersion("1.0.0");
            sysplugin.setPluginId("dxPhonePlugin");
            sysplugin.setPluginType(5);
            sysplugin.setIsInstalled(false);
            sysplugin.setIsEnabled(false);
            sysplugin.setMchId(mchId);
            sysplugin.setCreateDate(new Date());
            sysPluginService.insert(sysplugin);
            List<SysPluginAttribute> attributeList = new ArrayList<SysPluginAttribute>();
            for (int i = 0; i < 2; i ++) {
                SysPluginAttribute sysPluginAttribute = new SysPluginAttribute();
                sysPluginAttribute.setId(CodeGenerator.getUUID());
                sysPluginAttribute.setPluginId(sysPluginId);
                sysPluginAttribute.setType("1");
                if (0 == i) {
                    sysPluginAttribute.setName("custInteId");
                    sysPluginAttribute.setAttribute("WYKJ");
                } else if (1 == i) {
                    sysPluginAttribute.setName("secretKey");
                    sysPluginAttribute.setAttribute("JK-WYKJ");
                }
                attributeList.add(sysPluginAttribute);
            }
            sysPluginAttributeService.insertList(attributeList);
            sysplugin.setSysPluginAttribute(attributeList);
        }
        return sysplugin;
    }

    /**
     * 话费充值
     * @param sysPlugin
     * @param params
     * @throws IOException
     */
    @Override
    public void payPhoneBill(SysPlugin sysPlugin, Map<String,Object> params) throws IOException {
        Map<String, Object> xmlParam = new HashMap<String, Object>();
        //设置请求头参数
        String custInteId = sysPlugin.getAttribute("custInteId");//接入id
        String orderId = params.get("orderId").toString();//订单号
        String orderType = "1";//订单类型，订购
        String echo = UUID.randomUUID().toString();//随机数字
        String timestamp = DateUtils.getTimeStr(new Date(), DateUtils.DB_STORE_DATE);//时间戳
        String version = "1";//版本
        String chargeSign = null;
        try {
            chargeSign = Base64.encode(SecurityUtil.getDigestMD5(custInteId +
                    orderId + sysPlugin.getAttribute("secretKey") + echo + timestamp));
        } catch (Exception e) {
            e.printStackTrace();
        }
        xmlParam.put("custInteId", custInteId);
        xmlParam.put("orderId", orderId);
        xmlParam.put("orderType", orderType);
        xmlParam.put("echo", echo);
        xmlParam.put("timestamp", timestamp);
        xmlParam.put("version", version);
        xmlParam.put("chargeSign", chargeSign);
        xmlParam.put("info", params.get("info"));
        String xml = DxPhoneXmlUtil.buildOrderReqXml(xmlParam);
        String response = DXPhoneHttpUtil.requestPay(DxPhoneXmlUtil.url_order, xml);
        Map<String, Object> responseMap = DxPhoneXmlUtil.xmlToMap(response);
        if ("0000".equals(responseMap.get("result").toString())){
            logger.info("话费充值订购成功");
        } else {
            logger.info("话费充值订购失败");
        }
    }

    /**
     * 话费充值结果查询
     * @param sysPlugin
     * @param params
     * @return
     * @throws IOException
     */
    public Map<String, Object> orderQuery(SysPlugin sysPlugin, Map<String,Object> params) throws IOException {
        Map<String, Object> xmlParam = new HashMap<String, Object>();
        //设置请求头参数
        String custInteId = sysPlugin.getAttribute("custInteId");//接入id
        String echo = UUID.randomUUID().toString();//随机数字
        String timestamp = DateUtils.getTimeStr(new Date(), DateUtils.DB_STORE_DATE);//时间戳
        String version = "1";//版本
        String chargeSign = null;
        try {
            chargeSign = Base64.encode(SecurityUtil.getDigestMD5(custInteId + sysPlugin.getAttribute("secretKey")
                    + echo + timestamp));
        } catch (Exception e) {
            e.printStackTrace();
        }
        xmlParam.put("custInteId", custInteId);
        xmlParam.put("echo", echo);
        xmlParam.put("timestamp", timestamp);
        xmlParam.put("version", version);
        xmlParam.put("chargeSign", chargeSign);
        List<Map<String, Object>> queryOrderMapList = new ArrayList<Map<String, Object>>();
        Map<String, Object> queryOrderparam = new HashMap<String, Object>();
        queryOrderparam.put("orderIds", params.get("orderIds"));
        queryOrderMapList.add(queryOrderparam);
        xmlParam.put("info", queryOrderMapList);
        String queryOrderXml = DxPhoneXmlUtil.buildOrderQueryReqXml(xmlParam);
        String queryOrderResponse = DXPhoneHttpUtil.requestPay(DxPhoneXmlUtil.url_queryOrder, queryOrderXml);
        int strStartIndex = queryOrderResponse.indexOf("<body>");
        int strEndIndex = queryOrderResponse.indexOf("</body>");
        String bodyStr = queryOrderResponse.substring(strStartIndex, strEndIndex).substring("<body>".length());
        Map<String, Object> queryOrderResponseMap = DxPhoneXmlUtil.xmlToMap(bodyStr);
        return queryOrderResponseMap;
    }

}
